<template>
  <div class="container">
    <!-- 左侧：表单区域 -->
    <div class="left-panel">
      <a-card class="form-container glossy-card">
        <div class="header-section">
          <h2 class="title gradient-text">AI 艺术生成器</h2>
          <p class="subtitle">用文字创造视觉奇迹</p>
        </div>

        <a-form
          layout="vertical"
          :model="formData"
          :rules="rules"
          ref="formRef"
          @finish="handleSubmit"
          class="custom-form"
        >
          <a-form-item label="正向提示词" name="prompt">
            <a-textarea
              v-model:value="formData.prompt"
              placeholder="描绘你想象中的画面..."
              :auto-size="{ minRows: 4, maxRows: 6 }"
              class="textarea-with-icon"
            >
              <template #prefix>
                <bulb-outlined class="textarea-icon animate-blink" />
              </template>
            </a-textarea>
          </a-form-item>

          <a-form-item label="反向提示词" name="negativePrompt">
            <a-input
              v-model:value="formData.negativePrompt"
              placeholder="希望排除的内容..."
              class="input-with-icon"
            >
              <template #prefix>
                <stop-outlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <!-- 生成数量改为滑动输入 -->
          <a-form-item label="生成数量" name="n">
            <a-slider
              v-model:value="formData.n"
              :min="1"
              :max="4"
              :marks="{1: '1', 2: '2', 3: '3', 4: '4'}"
              class="custom-slider"
            />
          </a-form-item>

          <!-- 模型选择部分修改为 -->
          <a-form-item label="选择模型" name="model">
            <div class="model-selector">
              <div
                v-for="model in models"
                :key="model.value"
                class="model-card"
                :class="{ active: formData.model === model.value }"
                @click="handleModelSelect(model.value)"
              >
                <rocket-two-tone
                  :two-tone-color="model.color"
                  class="model-icon"
                  :style="{ fontSize: '24px' }"
                />
                <h4>{{ model.label }}</h4>
                <p>{{ model.description }}</p>
              </div>
            </div>
          </a-form-item>

          <!-- 比例选择改为按钮组 -->
          <a-form-item label="画面比例" name="ratio">
            <div class="ratio-selector">
              <div
                v-for="(size, ratio) in ratioMapping"
                :key="ratio"
                class="ratio-option"
                :class="{active: formData.ratio === ratio}"
                @click="formData.ratio = ratio"
              >
                <div class="ratio-box" :style="{aspectRatio: ratio}"></div>
                <span>{{ size }}</span>
              </div>
            </div>
          </a-form-item>

          <!-- 水印开关美化 -->
          <a-form-item label="版权保护" name="watermark">
            <a-switch
              v-model:checked="formData.watermark"
              checked-children="开启"
              un-checked-children="关闭"
              class="custom-switch"
            />
          </a-form-item>

          <!-- 动态进度条 -->
          <transition name="fade">
            <div v-if="taskId" class="progress-container">
              <div class="progress-header">
                <loading-outlined />
                <span>创作进行中... {{ progress }}%</span>
              </div>
              <a-progress
                :percent="progress"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }"
                :show-info="false"
                stroke-linecap="round"
              />
              <p class="tips">通常需要10-30秒，请耐心等待魔法发生...</p>
            </div>
          </transition>

          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              class="submit-btn glow-button"
              :loading="loading"
              size="large"
            >
              <template #icon><rocket-outlined /></template>
              开始创作
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <!-- 右侧：预览区域 -->
    <div class="right-panel">
      <a-card class="preview-card glossy-card">
        <h3 class="preview-title">作品画廊</h3>

        <div v-if="previewImages.length === 0" class="no-preview">
          <div class="empty-state">
            <picture-outlined class="empty-icon" />
            <p>您创作的AI艺术作品将在此展示</p>
          </div>
        </div>

        <div v-else class="preview-grid">
          <transition-group name="staggered-fade" tag="div">
            <div
              v-for="(img, index) in previewImages"
              :key="img.url"
              class="artwork-card"
              @mouseenter="hoverIndex = index"
              @mouseleave="hoverIndex = -1"
            >
              <div class="image-container">
                <img
                  :src="img.url"
                  alt="AI生成作品"
                  class="artwork-image"
                  :class="{hovered: hoverIndex === index}"
                />
                <div class="artwork-meta">
                  <span class="model-badge">{{ formData.model }}</span>
                  <span class="size-badge">{{ formData.size }}</span>
                </div>
                <div class="hover-overlay" :class="{show: hoverIndex === index}">
                  <eye-outlined class="view-icon" />
                </div>
              </div>
            </div>
          </transition-group>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, reactive, ref, watch } from 'vue'
import { createPictureTextToImageTaskUsingPost, getPictureTextToImageTaskUsingGet } from '@/api/pictureController'
import { message } from 'ant-design-vue'
// icons.js
import {
  BulbOutlined,
  StopOutlined,
  RocketTwoTone,
  LoadingOutlined,
  RocketOutlined,
  PictureOutlined,
  EyeOutlined
} from "@ant-design/icons-vue";


// 新增模型数据定义
const models = ref([
  {
    value: 'wanx2.1-t2i-plus',
    label: '高质量版本',
    description: '生成高分辨率精细图像 (约15秒)',
    color: '#1890ff'
  },
  {
    value: 'wanx2.1-t2i-turbo',
    label: '极速版本',
    description: '快速生成基础图像 (约5秒)',
    color: '#52c41a'
  }
])

// 新增模型选择处理
const handleModelSelect = (value: string) => {
  formData.model = value
  formRef.value.validateField('model') // 触发表单验证
}

// 定义各比例对应的固定分辨率
const ratioMapping: Record<string, string> = {
  '1:1': '1024*1024',
  '16:9': '1440*810',
  '9:16': '810*1440',
  '4:3': '1440*1080',
  '3:4': '1080*1440',
}

const formRef = ref()
const loading = ref(false)
// 用于存放后端返回的图像预览 URL 数组
const previewImages = ref<string[]>([])

// 表单数据，默认比例为 1:1，尺寸自动根据映射设置
const formData = reactive({
  prompt: '',
  negativePrompt: '',
  n: 1,
  model: '',
  ratio: '1:1',
  size: ratioMapping['1:1'],
  seed: undefined,
  watermark: true,
  promptExtend: false,
})

// 监听比例变化，自动更新尺寸
watch(
  () => formData.ratio,
  (newRatio) => {
    formData.size = ratioMapping[newRatio] || ''
  }
)

// 表单校验规则
const rules = {
  prompt: [
    { required: true, message: '正向提示词不能为空', trigger: 'blur' },
  ],
  n: [
    { required: true, message: '生成数量不能为空', trigger: 'blur' },
  ],
  model: [
    { required: true, message: '请选择模型', trigger: 'change' },
  ],
  ratio: [
    { required: true, message: '请选择图像比例', trigger: 'change' },
  ],
  size: [
    { required: true, message: '自动生成的图像尺寸不能为空', trigger: 'change' },
  ],
}

// 任务 id
let taskId = ref<string>()

// 进度条数值
const progress = ref<number>(0)

// 进度条定时器
let progressTimer: NodeJS.Timeout = null

/**
 * 启动进度条定时器，前10秒每秒增加10%，最多增加到99%
 */
const startProgressTimer = () => {
  progress.value = 0
  progressTimer = setInterval(() => {
    if (progress.value < 99) {
      progress.value += 10
      if (progress.value > 99) progress.value = 99
    }
  }, 1000)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate() // 校验表单
    loading.value = true
    // 调用后端创建文字生成图片任务接口
    const res = await createPictureTextToImageTaskUsingPost({ ...formData })
    if (res.data.code === 0 && res.data.data) {
      taskId.value = res.data.data.output.taskId
      // 启动进度条定时器
      startProgressTimer()
      // 开启轮询
      startPolling()
      message.success(`✅ 创建成功，共 ${formData.n} 张图片`)
    } else {
      message.error('❌ 创建失败：' + res.data.message)
    }
  } catch (error) {
    message.error('请填写完整信息')
  } finally {
    loading.value = false
  }
}

// 轮询定时器
let pollingTimer: NodeJS.Timeout = null

// 清理轮询定时器
const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}

/**
 * 清理进度条定时器
 */
const clearProgressTimer = () => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
}

// 开始轮询任务状态
const startPolling = () => {
  if (!taskId.value) return

  pollingTimer = setInterval(async () => {
    try {
      const res = await getPictureTextToImageTaskUsingGet({
        taskId: taskId.value,
      })
      if (res.data.code === 0 && res.data.data) {
        const taskResult = res.data.data.output
        if (taskResult.taskStatus === 'SUCCEEDED') {
          message.success('AI文字生成图片任务成功')
          // 如果返回的是单个 URL，则包装成数组，否则直接赋值
          if (typeof taskResult.results === 'string') {
            previewImages.value = [taskResult.results]
          } else {
            previewImages.value = taskResult.results
          }
          clearPolling()
          clearProgressTimer()
          progress.value = 100
        } else if (taskResult.taskStatus === 'FAILED') {
          message.error('I文字生成图片失败')
          clearPolling()
          clearProgressTimer()
          progress.value = 100
        }
      }
    } catch (error) {
      console.error('轮询任务状态失败', error)
      message.error('检测任务状态失败，请稍后重试')
      clearPolling()
      clearProgressTimer()
      progress.value = 100
    }
  }, 3000)
}

// 清理定时器，避免内存泄漏
onUnmounted(() => {
  clearPolling()
  clearProgressTimer()
})
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');


/* 新增模型选择器样式 */
.model-selector {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 8px;
}

.model-card {
  padding: 16px;
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: white;
}

.model-card:hover {
  border-color: #40a9ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
}

.model-card.active {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.model-card h4 {
  margin: 12px 0 8px;
  color: rgba(0, 0, 0, 0.85);
  font-size: 15px;
}

.model-card p {
  margin: 0;
  color: rgba(0, 0, 0, 0.65);
  font-size: 12px;
  line-height: 1.4;
}

.model-icon {
  display: block;
  margin: 0 auto;
}

.container {
  display: grid;
  grid-template-columns: 1fr 1.2fr;
  gap: 2rem;
  padding: 2rem;
  max-width: 1600px;
  margin: 0 auto;
  font-family: 'Inter', sans-serif;
}

.glossy-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 1.5rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

.header-section {
  text-align: center;
  margin-bottom: 2rem;

  .title {
    font-size: 2.2rem;
    margin: 0;
    background: linear-gradient(135deg, #434343 0%, #000000 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .subtitle {
    color: #666;
    margin-top: 0.5rem;
    font-weight: 500;
  }
}

.custom-form {
  .ant-form-item-label label {
    font-weight: 600;
    color: #333;
  }

  .input-with-icon {
    .input-icon {
      color: #1890ff;
      margin-right: 8px;
    }
  }
}

.model-selector {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;

  .model-card {
    padding: 1rem;
    border: 2px solid #eee;
    border-radius: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;

    &.active {
      border-color: #1890ff;
      background: #f0f9ff;
    }

    .model-icon {
      font-size: 2rem;
      margin-bottom: 0.5rem;
    }

    h4 {
      margin: 0.5rem 0;
      color: #333;
    }

    p {
      color: #666;
      font-size: 0.9em;
      margin: 0;
    }
  }
}

/* 图标闪烁动效 */
@keyframes blink {
  0% { opacity: 1; }
  50% { opacity: 0.3; }
  100% { opacity: 1; }
}

.textarea-with-icon .textarea-icon {
  margin: 0 10px;
  font-size: 18px;
  position: relative;
  top: 1px; /* 垂直对齐调整 */
}

.animate-blink {
  animation: blink 1.5s infinite;
}

/* 可选：调整输入框内边距 */
.ant-textarea {
  padding-left: 30px !important; /* 根据图标大小调整 */
}

.ratio-selector {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 1rem;

  .ratio-option {
    position: relative;
    cursor: pointer;
    border: 2px solid #eee;
    border-radius: 8px;
    padding: 0.5rem;
    transition: all 0.3s ease;

    &.active {
      border-color: #1890ff;
      background: #f0f9ff;
    }

    .ratio-box {
      width: 100%;
      background: #f8f8f8;
      border-radius: 4px;
    }

    span {
      display: block;
      text-align: center;
      margin-top: 0.5rem;
      font-size: 0.9em;
    }
  }
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  font-weight: 600;
  transition: all 0.3s ease;

  &.glow-button {
    background: linear-gradient(135deg, #434343 0%, #000000 100%);
    border: none;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    }
  }
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  padding: 1rem;

  .artwork-card {
    position: relative;
    border-radius: 1rem;
    overflow: hidden;
    transition: transform 0.3s ease;

    .image-container {
      position: relative;
      padding-top: 100%;
      background: #f8f8f8;

      .artwork-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;

        &.hovered {
          transform: scale(1.03);
        }
      }
    }

    .artwork-meta {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 0.5rem;
      background: linear-gradient(transparent, rgba(0,0,0,0.7));
      color: white;
      display: flex;
      justify-content: space-between;
      font-size: 0.8em;
    }

    .hover-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s ease;

      &.show {
        opacity: 1;
      }

      .view-icon {
        color: white;
        font-size: 2rem;
      }
    }
  }
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.staggered-fade-move,
.staggered-fade-enter-active,
.staggered-fade-leave-active {
  transition: all 0.5s ease;
}
.staggered-fade-enter-from,
.staggered-fade-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

@media (max-width: 768px) {
  .container {
    grid-template-columns: 1fr;
  }
}
</style>
